import axios from "axios"
import { Loading,Message } from "element-ui";
import router from "@/router"

let baseURL = "http://123.56.117.43:3000/"
axios.defaults.baseURL = baseURL


let load = null
export function showLoading(){
    load && load.close
    load = Loading.service({
        lock: true,
        text: '请求中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}

export function showSuccess(msg){
    msg = msg || "请求成功" 
    load && load.close() ; 
    Message.success({
        message: msg,
        center: true,
        duration:1200,
        showClose: true,
    })
}

export function showError(msg){
    msg = msg || "请求失败" 
    load && load.close() ; 
    Message.error({
        message: msg,
        center: true,
        showClose: true,
        duration:1200
    })
}



// 请求发送之前的拦截器
axios.interceptors.request.use(function(config){
    var token = sessionStorage.getItem("token");
    if(token){
        config.headers['token'] = token
    }
    showLoading()
    return config
}, function(error){
  
    showError()
    return Promise.reject(error)
});

axios.interceptors.response.use(function(response){

    setTimeout(()=>{
        if(response.data.type == 1){
            showSuccess(response.data.msg)
        }else{
            showError(response.data.msg)  
        }
      
   },800)

   if(response.data.code == 3200){
    router.push({name:"login"})
   }

    return response
}, function(error){
    showError('响应失败')
    return Promise.reject(error)
});

export const get = (url,params)=>{
    return new Promise (function(resolve,reject){
        axios.get(url,{
            params
        })
        .then(res=>{
            resolve(res.data)
        })
        .catch(err=>{
            reject(err)
        })
    })
}

export const post = (url,params)=>{
    return new Promise(function(resolve,reject){
        axios.post(url,params)
        .then(res=>{
            resolve(res.data)
        })
        .catch(err=>{
            reject(err)
        })
    })
}

export  {axios,baseURL}